package com.joysuch.wwyt.workflow.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.core.bean.BaseMenuFunctionEditBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseMenuFunction;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.repository.BaseMenuFunctionDao;
import com.joysuch.wwyt.core.service.BaseMenuFunctionService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.workflow.bean.WorkFlowInquiryConfigBean;
import com.joysuch.wwyt.workflow.bean.WorkFlowInquirySerachParam;
import com.joysuch.wwyt.workflow.entity.BaseSummaryInquiryConfig;
import com.joysuch.wwyt.workflow.entity.WorkFlowProcess;
import com.joysuch.wwyt.workflow.entity.dto.WorkFlowReportConfigDto;
import com.joysuch.wwyt.workflow.entity.vo.BaseSummaryInquiryConfigPageVO;
import com.joysuch.wwyt.workflow.enums.WorkFlowDataSourceEnum;
import com.joysuch.wwyt.workflow.enums.WorkFlowDisplayFormEnum;
import com.joysuch.wwyt.workflow.enums.WorkFlowInquiryTypeEnum;
import com.joysuch.wwyt.workflow.mapper.BaseSummaryInquiryConfigMapper;
import com.joysuch.wwyt.workflow.repository.WorkFlowProcessDao;
import com.joysuch.wwyt.workflow.service.BaseSummaryInquiryConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhaoqw
 * @since 2021-04-16
 */
@Service
public class BaseSummaryInquiryConfigServiceImpl extends ServiceImpl<BaseSummaryInquiryConfigMapper, BaseSummaryInquiryConfig> implements BaseSummaryInquiryConfigService {

    @Autowired
    private BaseMenuFunctionService baseMenuFunctionService;
    @Autowired
    private BaseMenuFunctionDao baseMenuFunctionDao;
    @Autowired
    private BaseSummaryInquiryConfigMapper configMapper;
    @Autowired
    private BaseSummaryInquiryConfigService service;
    @Autowired
    private WorkFlowProcessDao workFlowProcessDao;


    /**
     * 保存
     *
     * @param workFlowInquiryConfigBean
     * @return
     */
    @Override
    public void saveSummaryInquiryConfig(WorkFlowInquiryConfigBean workFlowInquiryConfigBean) {
        BaseSummaryInquiryConfig config;
        BaseMenuFunction menu = null;
        BaseMenuFunctionEditBean menuBean = new BaseMenuFunctionEditBean();
        //1.保存菜单
        if (workFlowInquiryConfigBean.getId() != null) {
            config = configMapper.selectById(workFlowInquiryConfigBean.getId());
            Optional<BaseMenuFunction> obf = baseMenuFunctionDao.findById(workFlowInquiryConfigBean.getMenuId());
            //判断菜单页面是否存在如:生成的菜单在菜单页面删除
            if (obf.isPresent()) {
                //修改菜单
                BeanUtils.copyProperties(obf.get(), menuBean);
                menuBean.setParentId(workFlowInquiryConfigBean.getParentMenuId());
                menuBean.setName(workFlowInquiryConfigBean.getReportName());
                menu = baseMenuFunctionService.update(menuBean);
            } else {
                //新增菜单
                menu = addBaseMenuFunction(menu, menuBean, workFlowInquiryConfigBean);
            }
        } else {
            config = new BaseSummaryInquiryConfig();
            //新增菜单
            menu = addBaseMenuFunction(menu, menuBean, workFlowInquiryConfigBean);
        }
        //2.保存报表配置
        BeanUtils.copyProperties(workFlowInquiryConfigBean, config);
        if (menu != null) {
            config.setMenuId(menu.getId());
        }
        String s = JSON.toJSONString(workFlowInquiryConfigBean.getProcessIds());
        config.setProcessIds(s);
        config.setReportConfig(JSON.toJSONString(workFlowInquiryConfigBean.getReportConfigs()));
        //修改-重新放入修改时间
        if (workFlowInquiryConfigBean.getId() != null) {
            config.setUpdateTime(new Date());
        }
        service.saveOrUpdate(config);
        //将报表统计id存入菜单表
        if (workFlowInquiryConfigBean.getId() == null && workFlowInquiryConfigBean.getMenuType().equals("T")) {
            Long configId = configMapper.selectByMenuId(menu.getId());
            menu.setInquiryId(configId);
            baseMenuFunctionDao.save(menu);
        }
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @Override
    public WorkFlowInquiryConfigBean findById(Long id) {
        WorkFlowInquiryConfigBean dto = new WorkFlowInquiryConfigBean();
        BaseSummaryInquiryConfig config = configMapper.selectById(id);
        if (config != null) {
            BeanUtils.copyProperties(config, dto);
            //流程名称
            if (StringUtils.isNotBlank(config.getProcessIds())) {
                List<String> processNames = new ArrayList<>();
                List<Long> processIds = JSON.parseArray(config.getProcessIds(), Long.TYPE);
                //流程名称
                if (!CollectionUtils.isEmpty(processIds)) {
                    dto.setProcessIds(processIds);
                    for (Long processId : processIds) {
                        Optional<WorkFlowProcess> owp = workFlowProcessDao.findById(processId);
                        if (owp.isPresent()) {
                            processNames.add(owp.get().getBizName());
                        }
                    }
                    dto.setProcessNames(processNames);
                }
            }
            //父菜单名称
            if (config.getMenuId() != null) {
                Optional<BaseMenuFunction> obf = baseMenuFunctionDao.findById(config.getMenuId());
                if (obf.isPresent()) {
                    BaseMenuFunction parent = obf.get().getParent();
                    if (parent != null) {
                        dto.setParentMenuName(parent.getName());
                        dto.setParentMenuId(parent.getId());
                    }
                }
            }
            //报表配置
            if (StringUtils.isNotBlank(config.getReportConfig())) {
                List<WorkFlowReportConfigDto> reportConfigs = JSONArray.parseArray(config.getReportConfig(), WorkFlowReportConfigDto.class);
                if (!CollectionUtils.isEmpty(reportConfigs)) {
                    dto.setReportConfigs(reportConfigs);
                }
            }
        }
        dto.setDataSourceName(WorkFlowDataSourceEnum.findNameByCode(dto.getDataSource()));
        dto.setInquiryTypeName(WorkFlowInquiryTypeEnum.findNameByCode(dto.getInquiryType()));
        dto.setDisplayForm(dto.getDisplayForm());
        return dto;
    }

    @Override
    public ResultBean findPage(WorkFlowInquirySerachParam param) {
        Page<BaseSummaryInquiryConfigPageVO> p = new Page<>();
        LambdaQueryWrapper<BaseSummaryInquiryConfig> wrapper = new QueryWrapper<BaseSummaryInquiryConfig>().lambda()
                .eq(BaseSummaryInquiryConfig::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode())
                .eq(BaseSummaryInquiryConfig::getTenentId,Context.getCurrentTenantId())
                .likeRight(BaseSummaryInquiryConfig::getOrgCode, Context.getCompanyCode())
                .orderByDesc(BaseSummaryInquiryConfig::getUpdateTime);
        if (StringUtils.isNotBlank(param.getName())) {
            wrapper.like(StringUtils.isNotBlank(param.getName()), BaseSummaryInquiryConfig::getReportName, param.getName());
        }
        IPage<BaseSummaryInquiryConfig> selectPage = configMapper.selectPage(new Page<BaseSummaryInquiryConfig>(param.getPage() + 1, param.getSize()), wrapper);
        Integer count = configMapper.selectCount(wrapper);
        List<BaseSummaryInquiryConfig> records = selectPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<BaseSummaryInquiryConfigPageVO> collect = records.stream().map(e -> {
                BaseSummaryInquiryConfigPageVO vo = new BaseSummaryInquiryConfigPageVO();
                BeanUtils.copyProperties(e, vo);
                //父菜单名称
                if (e.getMenuId() != null) {
                    Optional<BaseMenuFunction> obf = baseMenuFunctionDao.findById(e.getMenuId());
                    if (obf.isPresent()) {
                        BaseMenuFunction parent = obf.get().getParent();
                        if (parent != null) {
                            vo.setParentMenuName(parent.getName());
                        }
                    }
                }
                if (StringUtils.isNotBlank(e.getProcessIds())) {
                    List<Long> processIds = JSON.parseArray(e.getProcessIds(), Long.TYPE);
                    //流程名称
                    if (!CollectionUtils.isEmpty(processIds)) {

                        List<String> processNames = workFlowProcessDao.findNameByIds(processIds);
                        vo.setWorkFlowNames(StringUtils.join(processNames, ","));
                    }
                }
                //给前段名称
                vo.setDataSource(WorkFlowDataSourceEnum.findNameByCode(e.getDataSource()));
                vo.setInquiryType(WorkFlowInquiryTypeEnum.findNameByCode(e.getInquiryType()));
                vo.setDisplayForm(WorkFlowDisplayFormEnum.findNameByCode(e.getDisplayForm()));
                return vo;
            }).collect(Collectors.toList());
            p.setRecords(collect);
            p.setTotal(selectPage.getTotal());
        }
        return ResultBean.pageData(p.getRecords(), count);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean deleteById(Long id) {
        BaseSummaryInquiryConfig config = configMapper.selectById(id);
        configMapper.deleteById(id);
        if (config != null && config.getMenuId() != null) {
            Optional<BaseMenuFunction> obf = baseMenuFunctionDao.findById(config.getMenuId());
            if (obf.isPresent()) {
                baseMenuFunctionService.delete(config.getMenuId());
            }
        }
        return ResultBean.success("");
    }

    /**
     * 新增菜单
     *
     * @param function
     * @param menuBean
     * @param workFlowInquiryConfigBean
     * @return
     */
    private BaseMenuFunction addBaseMenuFunction(BaseMenuFunction function, BaseMenuFunctionEditBean menuBean, WorkFlowInquiryConfigBean workFlowInquiryConfigBean) {
        if (StringUtils.isNotBlank(workFlowInquiryConfigBean.getMenuType()) && workFlowInquiryConfigBean.getMenuType().equals("T")) {
            menuBean.setParentId(workFlowInquiryConfigBean.getParentMenuId());
            menuBean.setName(workFlowInquiryConfigBean.getReportName());
            //默认类型 菜单
            menuBean.setType("menu");
            menuBean.setMenuOrder(1000);
            menuBean.setUrl("/system-turn/summary-menu");
            return baseMenuFunctionService.add(menuBean);
        }
        return function;
    }

}
